<script setup lang="ts">
import { uploadPost } from '@/api/consult'
import { showFailToast } from 'vant'
import type { UploaderAfterRead } from 'vant/lib/uploader/types'
import { ref } from 'vue'

withDefaults(
  defineProps<{
    disabled: boolean
  }>(),
  {
    disabled: false
  }
)
const emits = defineEmits<{
  (e: 'sendTxt', x: string): void
  (e: 'sendImg', x: { id: string; url: string }): void
}>()
const msg = ref('')
const sendEvent = () => {
  if (msg.value === '') {
    return showFailToast('请先输入内容再发送')
  }
  emits('sendTxt', msg.value)
  // 清空输入框内容
  msg.value = ''
}

// 上传图片
const afterRead: UploaderAfterRead = async res => {
  if (Array.isArray(res)) {
    return
  }
  if (!res.file) {
    return
  }
  // 调用接口上传图片
  console.log(res)
  const res2 = await uploadPost(res.file)
  emits('sendImg', res2.data)
  console.log(res2.data)
}
</script>

<template>
  <div class="room-action">
    <van-field
      :disabled="!disabled"
      type="text"
      class="input"
      :border="false"
      v-model.trim="msg"
      placeholder="问医生"
      autocomplete="off"
      @keyup.enter="sendEvent"
    ></van-field>
    <van-uploader :disabled="!disabled" :preview-image="false" :after-read="afterRead">
      <cp-icon name="consult-img" />
    </van-uploader>
  </div>
</template>

<style lang="scss" scoped>
.room-action {
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
  height: 60px;
  background-color: #fff;
  display: flex;
  align-items: center;
  padding: 0 16px;
  z-index: 1;
  box-sizing: border-box;
  .input {
    background-color: var(--cp-bg);
    border: none;
    border-radius: 25px;
    margin-right: 10px;
    padding: 8px 15px;
  }
  .cp-icon {
    width: 24px;
    height: 24px;
  }
}
</style>
